package org.freemarker.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.freemarker.core.model.Car;
import org.freemarker.core.service.CarService;
import org.freemarker.core.validator.Validator;
import org.freemarker.web.custom.CustomHttpServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;


@Controller
public class CarUpdateController extends CustomHttpServlet {
	private static final long serialVersionUID = -2497669202834227397L;
	@Autowired
	private CarService carService;
	private Validator validator= new Validator();
	
	

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		req.getRequestDispatcher("views/car/updateCar.ftl").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		
		String marca = req.getParameter("marca");
		String model = req.getParameter("model");
		String numarMatricol = req.getParameter("numarMatricol");

		Car c = new Car();
		c.setMarca(marca);
		c.setModel(model);
		c.setNumarMatricol(numarMatricol);
		Car c2 = new Car();
		String updateError = new String();
		try {
			c2 = carService.getCarForNr(numarMatricol);
		} catch (Exception e) {
			updateError="Plate number not present in database!";
			List<Car> cars = carService.findAll();
			req.setAttribute("cars", cars);
			req.setAttribute("updateError",updateError);
			req.getRequestDispatcher("views/car/listCars.ftl")
					.forward(req, res);
			return;
		}

		List<String> errors= new ArrayList<String>();
		
		try {
			errors=validator.checkCarData(c);
			if(errors.size()>0){
				for(int i = 0; i < errors.size(); i++){
					System.out.println(errors.get(i));
					List<Car> cars = carService.findAll();

					req.setAttribute("cars", cars);
					req.setAttribute("errors",errors);
					req.getRequestDispatcher("views/car/listCars.ftl")
							.forward(req, res);
					return;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Car c3 = carService.getCarForNr(c.getNumarMatricol());
		c3.setMarca(c.getMarca());
		c3.setModel(c.getModel());
		carService.update(c3);
		List<Car> cars = carService.findAll();

		req.setAttribute("cars", cars);
		req.getRequestDispatcher("views/car/listCars.ftl")
				.forward(req, res);
	}

}
